package org.apimgr.controller;

import com.alibaba.fastjson.JSON;
import org.apimgr.annotation.AuthReq;
import org.apimgr.constants.StringConstants;
import org.apimgr.dto.ApiUserReqDto;
import org.apimgr.dto.ApiUserResDto;
import org.apimgr.exception.PTUnCheckedException;
import org.apimgr.service.ApiUserService;
import org.apimgr.service.LoginService;
import org.apimgr.util.RespJson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * Created by yangjie on 2017/8/2.
 */
@RestController
@RequestMapping("/user")
public class UserController {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Resource
    private ApiUserService apiUserService;

    @Resource
    private LoginService loginService;
    /**
     * 用户登录
     * @param reqDto
     * @return
     */
    @RequestMapping(value = "/login",method = {RequestMethod.GET,RequestMethod.POST})
    public RespJson login(@RequestBody ApiUserReqDto reqDto){
        logger.info("用户登录:"+ JSON.toJSON(reqDto));
        ApiUserResDto resDto = null;
        try {
            resDto = apiUserService.getLoginUser(reqDto);
        }catch (PTUnCheckedException e){
            return  RespJson.buildFailureResponse(e.getOutMsg());
        }catch (Exception e){
            e.printStackTrace();
            return  RespJson.buildFailureResponse(StringConstants.SYSTEM_ERROR);
        }

        return RespJson.buildSuccessResponse(resDto);
    }

    /**
     * 用户登出
     * @param token
     * @return
     */
    @RequestMapping(value = "/loginOut",method = {RequestMethod.GET,RequestMethod.POST})
    @AuthReq
    public RespJson loginOut( String token){
        logger.info("用户登出:"+ token);
        ApiUserResDto resDto = null;
        try {
            loginService.loginOut(token);
        }catch (PTUnCheckedException e){
            return  RespJson.buildFailureResponse(e.getOutMsg());
        }catch (Exception e){
            e.printStackTrace();
            return  RespJson.buildFailureResponse(StringConstants.SYSTEM_ERROR);
        }
        return RespJson.buildSuccessResponse(resDto);
    }
}
